import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next';
import PropsType from "prop-types";
import { TextField, Popover } from '@mui/material'
import MyTreeViewLazy from '../../MyTreeViewLazy'
import { searchDataById } from '../../../utils/util'
import { makeStyles } from 'tss-react/mui';
import GlobalLoading from '../../GlobalLoading';

const useProverClasses = makeStyles()(() =>({
  proverStyles: {
    '.MuiPopover-paper': {
      minWidth: '240px',
      padding: '16px',
      maxHeight: '350px'
    }
  }
}))

const MyTreeSelect = (props) => {
  const { classes } = useProverClasses()
  const { i18n: { language } } = useTranslation()
  const { label, variant, treeKeyProp, treeLabelProp, treeChildrenProp, getTreeDatas, onFocusGetTree, onChange, value, startAdornment, endAdornment} = props
  const [anchorEl, setAnchorEl] = useState(null)
  const open = Boolean(anchorEl)
  const [treeData, setTreeData] = useState([])
  const [Loading, setLoading] = useState(false)

  const initialTreeData = useCallback(async () => {
    try {
      setLoading(true)
      setTreeData([])
      const treeData = await getTreeDatas()
      setTreeData(treeData)
      setLoading(false)
    } catch (err) {
      console.log(err)
      setTreeData([])
      setLoading(false)
    }
  }, [getTreeDatas])

  const handleClick = useCallback((event) => {
    setAnchorEl(event.currentTarget)
    if (onFocusGetTree) {
      initialTreeData()
    }
  }, [initialTreeData, onFocusGetTree])

  const handleClose = useCallback(() => {
    setAnchorEl(null)
  }, [])

  const getInputValue = useCallback((value) => {
    if (!value) {
      return ''
    }
    const item = searchDataById(value, treeData, treeKeyProp, treeChildrenProp)
    if (item) {
      if (item[treeLabelProp].i18nValue) {
        if (item[treeLabelProp].i18nValue[language]) return item[treeLabelProp].i18nValue[language]
        return item[treeLabelProp].defaultValue
      }
      return item[treeLabelProp]
    }
    return ''
  }, [treeData, language, treeLabelProp, treeKeyProp, treeChildrenProp])

  const onNodeSelect = useCallback((_, nodeKey, nodeData) => {
    onChange(nodeData[treeKeyProp])
    handleClose()
  }, [treeKeyProp])

  useEffect(() => {
    if (!onFocusGetTree) {
      initialTreeData()
    }
  }, [])

  return (
    <div>
      <TextField
        value={getInputValue(value)}
        label={label}
        variant={variant}
        InputProps={{
          readOnly: true,
          startAdornment,
          endAdornment
        }}
        onClick={(event) => handleClick(event)}
      />
      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        className={classes.proverStyles}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
      >
        {
          Loading ? <GlobalLoading/> : (
            <MyTreeViewLazy
              treeData={treeData}
              onNodeSelect={onNodeSelect}
              proprtyRead={{
                nodeId: treeKeyProp,
                childrenpropety: treeChildrenProp,
                labelpropety: treeLabelProp
              }}
            ></MyTreeViewLazy>
          )
        }
      </Popover>
    </div>
  )
}

MyTreeSelect.propTypes = {
  label: PropsType.string,
  variant: PropsType.string,
  treeKeyProp: PropsType.string,
  treeLabelProp: PropsType.string,
  treeChildrenProp: PropsType.string,
  getTreeDatas: PropsType.func.isRequired,
  onFocusGetTree: PropsType.bool,
  value: PropsType.string,
  onChange: PropsType.func
}

MyTreeSelect.defaultProps = {
  label: '',
  variant: 'filled',
  treeKeyProp: 'id',
  treeLabelProp: 'name',
  treeChildrenProp: 'children',
  onFocusGetTree: false
}

export default MyTreeSelect